import { tagsStore } from './../../stores/tagsStore/index';
import { getToken } from '@/utils/auth';
import type { Router, _RouteRecordBase } from 'vue-router';
import { asyncRoute } from '../routes';
export const handleRouter = (router: Router) => {
  // 后置路由
  router.afterEach((to, form) => {
    console.log(to);
    if (to.meta && to.name && to.meta.needCache) {
      tagsStore().addCacheView(to.name.toString());
    }
    const { name, path, meta, params, query } = to;
    if (to.meta) {
      tagsStore().addVisitedView({ name, path, meta, params, query } as _RouteRecordBase);
    }
  });
  // 路由导航守卫
  let hasRoles = true;
  return router.beforeEach((to, form, next) => {
    if (getToken()) {
      if (to.path == '/login') {
        router.replace('/');
      }
      // 2.动态设置标题
      const title = import.meta.env.VITE_GLOB_APP_TITLE;
      document.title = to.meta?.name ? `${to.meta?.name} - ${title}` : title;
      if (hasRoles) {
        [asyncRoute()]?.forEach((item) => {
          router.addRoute(item as any);
        });
        hasRoles = false;
        next({ ...to });
      } else {
        next();
      }
    } else {
      const path = to.path;
      console.log(encodeURIComponent(path));

      to.path !== '/login'
        ? router.replace({
            path: '/login',
            query: { redirect: encodeURIComponent(JSON.stringify(path)) },
          })
        : next();
    }
  });
};
